package com.shop.trade.api.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.shop.common.model.PayCallMdel;
import com.shop.common.model.PayModel;
import com.shop.common.model.PayToUserModel;
import com.shop.common.model.ServiceBean;
import com.shop.common.tmpl.BaseService;
import com.shop.trade.api.service.IAliPaySvc;
import com.shop.trade.atom.atomsvc.IOrderAtomSvc;
import com.shop.trade.atom.atomsvc.IPayAtomSvc;
import com.shop.trade.feign.user.IUserAtomFeignClientSvc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年04月18日  11:14
 */
@Service
public class AliPaySvc extends BaseService implements IAliPaySvc {
    private static final Logger logger = LoggerFactory.getLogger(AliPaySvc.class);
    @Value("${pay.aliPay.privateKey}")
    private String privateKey;
    @Value("${pay.aliPay.publicKey}")
    private String publicKey;
    @Value("${pay.aliPay.appId}")
    private String appId;
    @Value("${pay.aliPay.callUrl}")
    private String callUrl;
    @Value("${pay.aliPay.serverUrl}")
    private String serverUrl;
    @Value("${pay.aliPay.successUrl}")
    private String successUrl;
    @Value("${pay.aliPay.callUrl2}")
    private String callUrl2;
    @Value("${pay.aliPay.successUrl2}")
    private String successUrl2;

    @Autowired
    IOrderAtomSvc iOrderAtomSvc;
    @Autowired
    IPayAtomSvc iPayAtomSvc;
    @Autowired
    IUserAtomFeignClientSvc iUserAtomFeignClientSvc;

    @Override
    public ServiceBean<String> payToUser(PayToUserModel payToUserModel) {
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, "json", "utf-8", publicKey, "RSA2");

        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":" + payToUserModel.getOut_biz_no() + "," +
                "\"payee_type\":\"ALIPAY_LOGONID\"," +//
                "\"payee_account\":" + payToUserModel.getPayee_account() + "," +
                "\"amount\":" + payToUserModel.getAmount() + "," +
                "\"payer_show_name\":" + payToUserModel.getPayer_show_name() + "," +
                "\"payee_real_name\":" + payToUserModel.getPayee_real_name() + "," +
                "\"remark\":" + payToUserModel.getRemark() + "" +
                "  }");
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.error("转账异常：" + e.getErrMsg());
            return resultFailed("提现失败");
        }
        if (response.isSuccess()) {



            return resultSuccess("提现成功");
        } else {
            return resultFailed("提现失败");
        }
    }

    @Override
    public void toPayPage(PayModel payModel, HttpServletResponse response) throws IOException {


        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, "json", "utf-8", publicKey, "RSA2");
        String callUrlStr="";
        if (payModel.getType()!=null&&payModel.getType()==2){
            callUrlStr = callUrl2;
        }else{
            callUrlStr=callUrl;
        }
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(callUrlStr);
        alipayRequest.setNotifyUrl(callUrlStr);//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "\"out_trade_no\":\"" + payModel.getOrderId() + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"total_amount\":\"" + payModel.getTotalAmount() + "\"," +
                "\"subject\":\"" + payModel.getSubject() + "\"," +
                "\"body\":\"" + payModel.getBody() + "\"," +
                "\"passback_params\":\"order_id%3d" + payModel.getOrderId() + "\"," +
                "\"extend_params\":{" +
                "\"sys_service_provider_id\":\"" + appId + "\"" +
                "}" +
                "  }");//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @Override
    public void aliPayCall(PayCallMdel payCallMdel, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        String url = successUrl + "?paytype=alipay" +
                "&trade_no=" + payCallMdel.getTrade_no() +
                "&out_trade_no=" + payCallMdel.getOut_trade_no() +
                "&seller_id=" + payCallMdel.getSeller_id() +
                "&total_amount=" + payCallMdel.getTotal_amount() +
                "&timestamp=" + payCallMdel.getTimestamp();
        response.getWriter().write("<script>window.location.href='" + url + "';</script>");
        response.getWriter().flush();
        response.getWriter().close();
    }

    @Override
    public void aliPayCall2(PayCallMdel payCallMdel, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        String url = successUrl2 + "?paytype=alipay" +
                "&trade_no=" + payCallMdel.getTrade_no() +
                "&out_trade_no=" + payCallMdel.getOut_trade_no() +
                "&total_amount=" + payCallMdel.getTotal_amount() +
                "&timestamp=" + payCallMdel.getTimestamp();
        response.getWriter().write("<script>window.location.href='" + url + "';</script>");
        response.getWriter().flush();
        response.getWriter().close();
    }
}
